import {GetQtController} from "../../../QtUtils";

self.importScripts('hcdecoder.js')

Module.onRuntimeInitialized=function ()
{
   onWasmLoaded();

}

HCDecodeWorker = function() {
	this.isConnected=false;
	this.decoder=Module;
	this.host=null;

	this.pts=0;
	this.logLevel=1;       //LOG_LEVEL_JS:0,LOG_LEVEL_WASM:1,LOG_LEVEL_FFMPEG:2
    this.decodeType=1;     //0:h264,1:h265
	this.wasmLoaded=false;

};

HCDecodeWorker.prototype ={
    constructor: HCDecodeWorker,
    initDecoder:function(){

        var videoCallback = this.decoder.addFunction(function (addr_y, addr_u, addr_v, stride_y, stride_u, stride_v, width, height, pts)
		{
			//console.log("[%d]In video callback, size = %d * %d, pts = %d", ++videoSize, width, height, pts)
			let size = width * height + (width / 2)  * (height / 2) + (width / 2)  * (height / 2)
			let data = new Uint8Array(size)
			let pos = 0
			for(let i=0; i< height; i++) {
				let src = addr_y + i * stride_y
				let tmp = HEAPU8.subarray(src, src + width)
				tmp = new Uint8Array(tmp)
				data.set(tmp, pos)
				pos += tmp.length
			}
			for(let i=0; i< height / 2; i++) {
				let src = addr_u + i * stride_u
				let tmp = HEAPU8.subarray(src, src + width / 2)
				tmp = new Uint8Array(tmp)
				data.set(tmp, pos)
				pos += tmp.length
			}
			for(let i=0; i< height / 2; i++) {
				let src = addr_v + i * stride_v
				let tmp = HEAPU8.subarray(src, src + width / 2)
				tmp = new Uint8Array(tmp)
				data.set(tmp, pos)
				pos += tmp.length
			}

			self.postMessage({type:3,data: data,width,height});
		});

		this.decoder._closeDecoder();

		var ret = this.decoder._openDecoder(this.decodeType, videoCallback, this.logLevel);
		if(ret == 0)
		{
			console.log("openDecoder success");
		}
		else
		{
			console.error("openDecoder failed with error", ret);
		}



	},
    init:function(theHost)
    {

        this.host=theHost;

    },
	start:function()
	{
		if(this.host)
		{
      let preHost = 'ws://';
      if(GetQtController().inParam.dataUrl.indexOf('https') != -1) {
        preHost = 'wss://';
      }
			this.webDataSocket = new WebSocket(preHost + this.host+'/');
			if(!this.webDataSocket)
			{

				return;
			}

			this.webDataSocket.binaryType = 'arraybuffer';
			this.webDataSocket.onopen = this.onDataSocketOpen.bind(this);
			this.webDataSocket.onmessage = this.onData.bind(this);
			this.webDataSocket.onclose = null;
			self.postMessage({type:1});
		}
		else
		{
			self.postMessage({type:2});
		}

	},
    startDataSession:function()
    {
        if(this.webDataSocket)
        {
            if(this.webDataSocket.readyState === WebSocket.OPEN)
            {
                this.isConnected = true;
            }
            else
            {
                console.log("try 'startDataSession' but socket is not connected yet");
            }
        }
    },

    onDataSocketOpen:function()
    {
        setTimeout(this.startDataSession.bind(this),1500);
    },
    onData:function(event)
    {
	    this.dataArray = new Uint8Array(event.data);
		var size = this.dataArray.length;
		var cacheBuffer = this.decoder._malloc(size);
		if (cacheBuffer != null)
		{
			this.decoder.HEAPU8.set(this.dataArray, cacheBuffer);
			this.decoder._decodeData(cacheBuffer, size, this.pts++);
			this.decoder._free(cacheBuffer);
		}


	},


}


self.decoder = new HCDecodeWorker();

this.onmessage = function(event)
{
	if(event.data.type==1)
	{
		self.decoder.init(event.data.dataHost)
	}
	else if(event.data.type==2)
	{
		self.decoder.init(event.data.dataHost);
		self.decoder.start();
	}


}

function onWasmLoaded() {

	self.decoder.initDecoder();
	self.decoder.start();


}


